package com.ordertracker.endpoint;

import com.ordertracker.Application;
import com.ordertracker.protocol.CommandMessage;
import com.ordertracker.security.ApplicationSecurityContext;
import com.ordertracker.service.ActionType;
import com.ordertracker.service.HandleChain;
import com.sun.jersey.spi.container.ContainerRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import java.io.Serializable;

/**
 * Description of class.
 * Created 2/12/13 4:39 PM
 *
 * @author andrey.rodin@playtech.com
 */
@Component
@Path("/documents")
public class DocumentEndPoint<T extends Serializable> {

    private static Logger logger = Logger.getLogger(DocumentEndPoint.class);

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{docName}/{actionName}")
    public Response handleMessage(@Context Request request, @PathParam("docName") String docName, @PathParam("actionName") String actionName, CommandMessage msg) {
        HandleChain bean = (HandleChain) Application.getApplication().getConfig().getContext().getBean(docName);
        ApplicationSecurityContext securityContext = (ApplicationSecurityContext)(((ContainerRequest) request).getSecurityContext()) ;
        Response response = null;
        try{
            response = bean.handleMessage(securityContext.getSession(), msg, ActionType.byName(actionName));
        } catch (WebApplicationException we) {
            Response.status(we.getResponse().getStatus()).build();
        } catch (Exception ex) {
            Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }

        return response;
    }
}
